package cn.xique.smartlock.web.front;

import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import io.jboot.web.controller.JbootController;
import io.jpress.module.smLock.model.LockHistory;
import io.jpress.module.smLock.service.LockHistoryService;

import javax.inject.Inject;
import java.util.Date;

//存储柜管理接口
public class CabinetController extends JbootController {

    @Inject
    private LockHistoryService lockHistoryService;
    //更新设备占用状态
    public Ret UpdateLockStatus(){
        String jsonString = HttpKit.readData(getRequest());
        LockHistory lockHistory = FastJson.getJson().parse(jsonString, LockHistory.class);
        Ret ret = Ret.create();
        //检查参数
        if(lockHistory == null
            || (lockHistory.getLockLockerid() == null )
            || (lockHistory.getLockUserid()<0) ){
            return ret.setFail().set("errormsg", "参数不合法");
        }

        //查询一下该锁是占用还是释放的
        LockHistory lockHistory1 = lockHistoryService.findByCabinetIdOccupy(lockHistory.getLockLockerid());

        if(lockHistory.getOccupy()){//表示当前请求开锁，
            //这里需要检测是否已经处于归还状态，否则返回错误

            if(lockHistory1 != null){
                return ret.setFail().set("errormsg", "该锁还在占用中");
            }

            lockHistory.setStarttime(new Date());
            lockHistoryService.save(lockHistory);


        }else{//这里请求释放柜子
            //查询还在未归还的占用记录
            if(lockHistory1 == null){
                return ret.setFail().set("errormsg", "该锁还在空闲状态");
            }
            lockHistory1.setOccupy(false);//释放柜子
            lockHistory1.setEndtime(new Date());
            lockHistoryService.update(lockHistory1);
        }
        return ret.setOk();
    }
}
